#include "spectrallineframe.h"
#include "ui_spectrallineframe.h"

#include"sourcemanage.h"
#include"delegate.h"

SpectralLineFrame::SpectralLineFrame(QWidget *parent,AnalyteDataBase *pAnalyteDataBase,int type) :
    QFrame(parent),
    ui(new Ui::SpectralLineFrame)
{
    ui->setupUi(this);
    this->type=type;
    //load
    if(pAnalyteDataBase==NULL)
    {
       this->pAnalyteDataBase=new AnalyteDataBase; //
    }
    this->pAnalyteDataBase=pAnalyteDataBase;

    pElementTableFrame=new ElementTableFrame(this,this->pAnalyteDataBase,1);
    ui->verticalLayout_Add->addWidget(pElementTableFrame,1);
    connect(pElementTableFrame,SIGNAL(SIG_Clicked(int,QString)),this,SLOT(OnElementChanged(int,QString)));
    connect(ui->listWidget_Base,SIGNAL(clicked(QModelIndex)),this,SLOT(OnCurrentRowChangedBase(QModelIndex)));
    connect(ui->listWidget_Muti,SIGNAL(clicked(QModelIndex)),this,SLOT(OnCurrentRowChangedMulti(QModelIndex)));
    connect(ui->lineEdit_Rsf,SIGNAL(editingFinished()),this,SLOT(OnValueChanged()));
    connect(ui->lineEdit_AtomicNum,SIGNAL(editingFinished()),this,SLOT(OnValueChanged()));
    connect(ui->lineEdit_First,SIGNAL(editingFinished()),this,SLOT(OnValueChanged()));
    connect(ui->lineEdit_Second,SIGNAL(editingFinished()),this,SLOT(OnValueChanged()));

    ui->tableWidget_EleAttribute->setContextMenuPolicy(Qt::CustomContextMenu);
    ui->tableWidget_Forbid->setContextMenuPolicy(Qt::CustomContextMenu);
    ui->listWidget_Base->setContextMenuPolicy(Qt::CustomContextMenu);
    ui->listWidget_Muti->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui->tableWidget_EleAttribute,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(OnCustomContextMenuRequested(QPoint)));
    connect(ui->tableWidget_Forbid,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(OnCustomContextMenuRequested(QPoint)));
    connect(ui->listWidget_Base,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(OnCustomContextMenuRequested(QPoint)));
    connect(ui->listWidget_Muti,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(OnCustomContextMenuRequested(QPoint)));
    pMenu = new QMenu(this);
    pMenu->addAction(ui->actionAdd);
    pMenu->addAction(ui->actionDel);

    CheckBox *pCheckBox=new CheckBox(this,0);
    ui->tableWidget_EleAttribute->setItemDelegateForColumn(0,pCheckBox);
    pCheckBox=new CheckBox(this,0);
    ui->tableWidget_EleAttribute->setItemDelegateForColumn(1,pCheckBox);
    pCheckBox=new CheckBox(this,0);
    ui->tableWidget_EleAttribute->setItemDelegateForColumn(2,pCheckBox);
    pCheckBox=new CheckBox(this,0);
    ui->tableWidget_EleAttribute->setItemDelegateForColumn(3,pCheckBox);
    LineEditDelegate *pLineEdit=new LineEditDelegate(this,2);
    ui->tableWidget_EleAttribute->setItemDelegateForColumn(5,pLineEdit);
    pLineEdit=new LineEditDelegate(this,0);
    ui->tableWidget_EleAttribute->setItemDelegateForColumn(6,pLineEdit);

    LoadData();
}

SpectralLineFrame::~SpectralLineFrame()
{
    if(pAnalyteDataBase!=NULL&&type==3)//谱线
    {
        delete pAnalyteDataBase;
    }
    delete ui;
}

void SpectralLineFrame::EnableSetPara(bool state)
{
//    disconnect(ui->tableWidget_Hop,SIGNAL(itemChanged(QTableWidgetItem*)),
//               this,SLOT(on_tableWidget_Hop_itemChanged(QTableWidgetItem*)));

//    int row,column;
//    row=ui->tableWidget_Hop->rowCount();
//    column=ui->tableWidget_Hop->columnCount();
//    for(int i=0;i<row;i++)
//    {
//        for(int j=0;j<column;j++)
//        {
//            if(j==3||j==4||j==9||j==10)
//            {
//                QTableWidgetItem *pItem=ui->tableWidget_Hop->item(i,j);
//                pItem->setFlags(Qt::NoItemFlags|Qt::ItemIsSelectable|Qt::ItemIsEnabled);
//            }
//            else
//            {
//                if(state==true)
//                {
//                    QTableWidgetItem *pItem=ui->tableWidget_Hop->item(i,j);
//                    pItem->setFlags(Qt::NoItemFlags|Qt::ItemIsSelectable|Qt::ItemIsEnabled|Qt::ItemIsEditable);
//                }
//                else
//                {
//                    QTableWidgetItem *pItem=ui->tableWidget_Hop->item(i,j);
//                    pItem->setFlags(Qt::NoItemFlags|Qt::ItemIsSelectable|Qt::ItemIsEnabled);
//                }
//            }
//        }
//    }

//    connect(ui->tableWidget_Sweep,SIGNAL(itemChanged(QTableWidgetItem*)),
//               this,SLOT(on_tableWidget_Sweep_itemChanged(QTableWidgetItem*)));
}

void SpectralLineFrame::LoadData()
{
    ui->tableWidget_EleAttribute->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    ui->tableWidget_Forbid->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    //ui->tableWidget_Forbid->verticalHeader()->setDefaultAlignment(Qt::AlignCenter);
    QAbstractItemModel *pModel=ui->tableWidget_Forbid->model();
    QList<QPair<double,double> > forbidRangs=pAnalyteDataBase->GetForbidRangs();
    int count=forbidRangs.count();
    ui->tableWidget_Forbid->setRowCount(count);
    for(int i=0;i<count;i++)
    {
        pModel->setData(pModel->index(i,0),QVariant(forbidRangs.at(i).first),Qt::DisplayRole);
        pModel->setData(pModel->index(i,1),QVariant(forbidRangs.at(i).second),Qt::DisplayRole);
    }

    //ui->listWidget_Base->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    //ui->listWidget_Base->verticalHeader()->setDefaultAlignment(Qt::AlignCenter);
    QHash<QString,EleAttributes> elementBaseTable=pAnalyteDataBase->GetElementBaseTable();
    ui->listWidget_Base->clear();
    ui->listWidget_Base->addItems(elementBaseTable.keys());

    QHash<QString,EleAttributes> elementMutiTable=pAnalyteDataBase->GetElementMutiTable();
    ui->listWidget_Muti->clear();
    ui->listWidget_Muti->addItems(elementMutiTable.keys());

    switch(type)
    {
        case 0:
        break;
        case 1://实验
            ui->pushButton_Save->setVisible(false);
            ui->frame_Forbid->setVisible(false);
            ui->tableWidget_EleAttribute->setColumnHidden(0,true);
            //ui->tableWidget_EleAttribute->setColumnHidden(1,true);
            ui->tableWidget_EleAttribute->setColumnHidden(2,true);
            ui->tableWidget_EleAttribute->setColumnHidden(3,true);
            //EnableSetPara(bool state);

            pMenu->clear();
        break;
        case 2://调谐?
            ui->pushButton_Save->setVisible(false);
            ui->frame_Forbid->setVisible(false);
            ui->tableWidget_EleAttribute->setColumnHidden(0,true);
            //ui->tableWidget_EleAttribute->setColumnHidden(1,true);
            ui->tableWidget_EleAttribute->setColumnHidden(2,true);
            ui->tableWidget_EleAttribute->setColumnHidden(3,true);

            pMenu->clear();
        break;
        case 3://谱线
            ui->pushButton_Add->setVisible(false);
            ui->pushButton_Delete->setVisible(false);
            ui->tableWidget_EleAttribute->setColumnHidden(0,true);
            ui->tableWidget_EleAttribute->setColumnHidden(1,true);
            //ui->tableWidget_EleAttribute->setColumnHidden(2,true);
            //ui->tableWidget_EleAttribute->setColumnHidden(3,true);
            pMenu->clear();
            pMenu->addAction(ui->actionAdd);
            pMenu->addAction(ui->actionDel);
        break;
    }
}

void SpectralLineFrame::ShowElementAttribute(int id,QString name)
{ 
    QHash<QString,EleAttributes> elementTable=pAnalyteDataBase->GetElements(tableType);
    if(elementTable.contains(name)==false) return;
    EleAttributes eleAttributes=elementTable.value(name);
    ui->label_Name->setText(name);
    ui->lineEdit_Rsf->setText(QString::number(eleAttributes.rsf));
    ui->lineEdit_AtomicNum->setText(QString::number(eleAttributes.atomicNum));
    ui->lineEdit_First->setText(QString::number(eleAttributes.energyFirst));
    ui->lineEdit_Second->setText(QString::number(eleAttributes.energySecond));
    //ui->label_Other->setText(QString("原子序数 %1;第一电离势能 %2;第二电离势能 %3")
    //        .arg(eleAttributes.atomicNum).arg(eleAttributes.energyFirst).arg(eleAttributes.energySecond));

    disconnect(ui->tableWidget_EleAttribute,SIGNAL(itemChanged(QTableWidgetItem*)),
               this,SLOT(on_tableWidget_EleAttribute_itemChanged(QTableWidgetItem*)));

    QHash<QString,EleAttributeBase> eleAttributeBases=eleAttributes.GetEleAttributes();
    int count=eleAttributeBases.count();
    ui->tableWidget_EleAttribute->setRowCount(count);
    int row=0;
    foreach(EleAttributeBase element,eleAttributeBases)
    {
        int column=0;
        QTableWidgetItem *pItem;
        pItem=new QTableWidgetItem;
        pItem->setText(QString::number(element.bIsForbid));
        pItem->setFlags(Qt::NoItemFlags|Qt::ItemIsSelectable|Qt::ItemIsEnabled);
        ui->tableWidget_EleAttribute->setItem(row,column++,pItem);
        pItem=new QTableWidgetItem;
        pItem->setText(QString::number(element.bIsChoose));
        pItem->setFlags(Qt::NoItemFlags|Qt::ItemIsSelectable|Qt::ItemIsEnabled);
        ui->tableWidget_EleAttribute->setItem(row,column++,pItem);
        pItem=new QTableWidgetItem;
        pItem->setText(QString::number(element.bIsUsed));
        pItem->setFlags(Qt::NoItemFlags|Qt::ItemIsSelectable|Qt::ItemIsEnabled);
        ui->tableWidget_EleAttribute->setItem(row,column++,pItem);
        pItem=new QTableWidgetItem;
        pItem->setText(QString::number(element.bIsDefault));
        pItem->setFlags(Qt::NoItemFlags|Qt::ItemIsSelectable|Qt::ItemIsEnabled);
        ui->tableWidget_EleAttribute->setItem(row,column++,pItem);
        pItem=new QTableWidgetItem;
        pItem->setText(element.name);
        pItem->setFlags(Qt::NoItemFlags|Qt::ItemIsSelectable|Qt::ItemIsEnabled);
        ui->tableWidget_EleAttribute->setItem(row,column++,pItem);
        pItem=new QTableWidgetItem;
        pItem->setText(QString::number(element.massNum));
        ui->tableWidget_EleAttribute->setItem(row,column++,pItem);
        pItem=new QTableWidgetItem;
        pItem->setText(QString::number(element.abundance));
        ui->tableWidget_EleAttribute->setItem(row,column++,pItem);
        pItem=new QTableWidgetItem;
        pItem->setText(element.formula);
        ui->tableWidget_EleAttribute->setItem(row,column++,pItem);
        pItem=new QTableWidgetItem;
        pItem->setText(element.interferRef);
        ui->tableWidget_EleAttribute->setItem(row,column++,pItem);
        row++;
    }

   connect(ui->tableWidget_EleAttribute,SIGNAL(itemChanged(QTableWidgetItem*)),
               this,SLOT(on_tableWidget_EleAttribute_itemChanged(QTableWidgetItem*)));
}
void SpectralLineFrame::OnElementChanged(int id,QString name)
{
    elementName=name;
    tableType=0;
    ShowElementAttribute( 0, elementName);
    ui->widget_Other->setVisible(true);
}
void SpectralLineFrame::OnCurrentRowChangedMulti(QModelIndex index)
{
    QString name=index.data().toString();
    elementName=name;
    tableType=1;

    ShowElementAttribute( 0, elementName);
    ui->widget_Other->setVisible(false);
}
void SpectralLineFrame::OnCurrentRowChangedBase(QModelIndex index)
{
    QString name=index.data().toString();
    elementName=name;
    tableType=2;

    ShowElementAttribute( 0, elementName);
    ui->widget_Other->setVisible(false);
}

//
bool SpectralLineFrame::SetFileName(QString name)
{
    fileName=name;
    return true;
}
QString SpectralLineFrame::GetFileName()
{
    return fileName;
}
/*
void SpectralLineFrame::contextMenuEvent(QContextMenuEvent *event)
{
    qDebug()<<"contextMenuEvent(QContextMenuEvent *)"<<event;
}
*/
int SpectralLineFrame::SaveData()
{
    QString filePath;
    if(fileName.contains(FM->GetDataBaseSuffix())==false)
    {
        filePath=QFileDialog::getSaveFileName(this, tr("Save File"),FM->GetDataBaseDir(),
                                              tr("Bin files (*%1)").arg(FM->GetDataBaseSuffix()));
        if(filePath=="") return 0;
    }
    else//
    {
        filePath=FM->GetDataBaseDir()+fileName;
    }
    qDebug()<<"SpectralLineFrame::SaveData filePath"<<filePath;
    FM->SaveToFile(filePath,pAnalyteDataBase);
    return 1;
}

void SpectralLineFrame::on_tableWidget_EleAttribute_itemChanged(QTableWidgetItem *item)
{
    QAbstractItemModel *pModel=ui->tableWidget_EleAttribute->model();
    EleAttributeBase element;

    element.bIsForbid=pModel->data(pModel->index(item->row(),0),Qt::DisplayRole).toBool();
    element.bIsChoose=pModel->data(pModel->index(item->row(),1),Qt::DisplayRole).toBool();
    element.bIsUsed=pModel->data(pModel->index(item->row(),2),Qt::DisplayRole).toBool();
    element.bIsDefault=pModel->data(pModel->index(item->row(),3),Qt::DisplayRole).toBool();
    element.name=pModel->data(pModel->index(item->row(),4)).toString();
    element.massNum=pModel->data(pModel->index(item->row(),5)).toDouble();
    element.abundance=pModel->data(pModel->index(item->row(),6)).toDouble();
    element.formula=pModel->data(pModel->index(item->row(),7)).toString();
    element.interferRef=pModel->data(pModel->index(item->row(),8)).toString();

    pAnalyteDataBase->SetEleAttribute(element.name,element,elementName,tableType);

    if(item->column()==1)//
    {
        emit SIG_ElementChooseChanged(element.bIsChoose,element.name);
    }
}
void SpectralLineFrame::OnValueChanged()
{
    double value;
    value=ui->lineEdit_Rsf->text().toDouble();
    pAnalyteDataBase->SetEleRsf(value,elementName,tableType);
    value=ui->lineEdit_AtomicNum->text().toDouble();
    pAnalyteDataBase->SetEleAtomicNum(value,elementName,tableType);
    value=ui->lineEdit_First->text().toDouble();
    pAnalyteDataBase->SetEleEnergyFirst(value,elementName,tableType);
    value=ui->lineEdit_Second->text().toDouble();
    pAnalyteDataBase->SetEleEnergySecond(value,elementName,tableType);
}

//menu
void SpectralLineFrame::on_actionDel_triggered()
{
    switch(menuType)
    {
        case 0:
            {
                int row=ui->tableWidget_EleAttribute->currentRow();
                QString massName;
                double massNum;
                double abundance;
                massNum=ui->tableWidget_EleAttribute->item(row,5)->text().toDouble();
                abundance=ui->tableWidget_EleAttribute->item(row,6)->text().toDouble();
                massName=ui->tableWidget_EleAttribute->item(row,4)->text();
                EleAttributeBase element(massName,massNum,abundance);
                pAnalyteDataBase->RemoveEleAttribute(massName,element,elementName,tableType);

                ShowElementAttribute(0,elementName);
             }
        break;
        case 1:
            {
                int row=ui->listWidget_Muti->currentRow();
                QString massName;
                massName=ui->listWidget_Muti->item(row)->text();
                EleAttributes element;
                pAnalyteDataBase->RemoveEleAttributes(element,massName,tableType);

                LoadData();
                ShowElementAttribute(0,"");//
             }
        break;
        case 2:
            {
                int row=ui->listWidget_Base->currentRow();
                QString massName;
                massName=ui->listWidget_Base->item(row)->text();
                EleAttributes element;
                pAnalyteDataBase->RemoveEleAttributes(element,massName,tableType);

                LoadData();
                ShowElementAttribute(0,"");//
             }
        break;
        case 3:
        break;
    }

}

void SpectralLineFrame::on_actionAdd_triggered()
{
    switch(menuType)
    {
        case 0:
            {
                double massNum=1;
                double abundance=1;
                QString massName=QString::number(qRound(massNum))+elementName;
                EleAttributeBase element(massName,massNum,abundance);
                pAnalyteDataBase->InsertEleAttribute(massName,element,elementName,tableType);

                ShowElementAttribute(0,elementName);
            }
        break;
        case 1:
            {
                //周期表中获取
                elementName="multi ele";
                EleAttributes element;
/*
                QString massName;
                double massNum;
                double abundance;
                massNum=1;
                abundance=1;
                massName=QString::number(massNum)+elementName;
                EleAttributeBase elementBase(massName,massNum,abundance);
                element.InsertElement(elementName,elementBase);
                element.InsertElement(elementName,elementBase);
                */
                pAnalyteDataBase->InsertEleAttributes(element,elementName,tableType);

                LoadData();
                ShowElementAttribute(0,elementName);
            }
        break;
        case 2:
            {
                //周期表中获取
                elementName="sigle ele";
                EleAttributes element;
/*
                QString massName;
                double massNum;
                double abundance;
                massNum=1;
                abundance=1;
                massName=QString::number(massNum)+elementName;
                EleAttributeBase elementBase(massName,massNum,abundance);
                element.InsertElement(elementName,elementBase);
                element.InsertElement(elementName,elementBase);
                */
                pAnalyteDataBase->InsertEleAttributes(element,elementName,tableType);

                LoadData();
                ShowElementAttribute(0,elementName);
            }
        break;
        case 3:
        break;
    }
}

void SpectralLineFrame::OnCustomContextMenuRequested(const QPoint &pos)
{
    QRect rect1(ui->tableWidget_EleAttribute->mapToGlobal(QPoint(0,0)),ui->tableWidget_EleAttribute->size());
    QRect rect2(ui->listWidget_Muti->mapToGlobal(QPoint(0,0)),ui->listWidget_Muti->size());
    QRect rect3(ui->listWidget_Base->mapToGlobal(QPoint(0,0)),ui->listWidget_Base->size());
    QRect rect4(ui->tableWidget_Forbid->mapToGlobal(QPoint(0,0)),ui->tableWidget_Forbid->size());
    if(rect1.contains(QCursor::pos()))
    {
       menuType=0;
    }
    else if(rect2.contains(QCursor::pos()))
    {
       menuType=1;
    }
    else if(rect3.contains(QCursor::pos()))
    {
       menuType=2;
    }
    else if(rect4.contains(QCursor::pos()))
    {
       menuType=3;
    }

    //qDebug()<<"rect1"<<rect1<<"rect2"<<rect2<<"rect3"<<rect3<<"rect4"<<rect4;
    //qDebug()<<"menuType"<<menuType;
    //qDebug()<<"QCursor::pos()"<<QCursor::pos()<<"pos"<<pos<<QWidget::mapToGlobal(pos);

    pMenu->exec(QCursor::pos());//在当前鼠标位置显示
}
